﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Net.Http;

namespace BW.Mes.WinForms.BasicData
{
    public partial class BomForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient = new HttpClient();
        private readonly string _bomApiBaseUrl = "https://localhost:7274";

        public BomForm()
        {
            InitializeComponent();
            this.Load += BomForm_Load;
            gridView1.CustomUnboundColumnData += gridView1_CustomUnboundColumnData;
        }

        private async void BomForm_Load(object sender, EventArgs e)
        {
            await LoadBomData();
        }

        private async Task LoadBomData()
        {
            try
            {
                var result = await GetApiDataAsync<BomListResponse>("api/Bom/GetBom");
                gridControl1.DataSource = null;
                gridControl1.DataSource = result.pageDatas;
                gridView1.PopulateColumns();
                gridView1.BestFitColumns();
                gridView1.RefreshData();
                AfterBindBomData();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}", "错误");
            }
        }

        private async Task<T> GetApiDataAsync<T>(string endpoint)
        {
            HttpResponseMessage response = await _httpClient.GetAsync($"{_bomApiBaseUrl}/{endpoint}");
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<T>(responseBody);
        }

        private void SetupGridActionColumn()
        {
            var actionColumn = new DevExpress.XtraGrid.Columns.GridColumn();
            actionColumn.Caption = "操作";
            actionColumn.Name = "ActionColumn";
            actionColumn.Visible = true;
            actionColumn.VisibleIndex = 9;
            actionColumn.Width = 240;
            actionColumn.MinWidth = 240;
            actionColumn.ColumnEdit = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
            var buttonEdit = actionColumn.ColumnEdit as DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit;
            buttonEdit.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
            buttonEdit.Buttons.Clear();
            var editButton = new DevExpress.XtraEditors.Controls.EditorButton();
            editButton.Caption = "修改";
            editButton.Width = 60;
            buttonEdit.Buttons.Add(editButton);
            var deleteButton = new DevExpress.XtraEditors.Controls.EditorButton();
            deleteButton.Caption = "删除";
            deleteButton.Width = 60;
            buttonEdit.Buttons.Add(deleteButton);
            buttonEdit.ButtonClick += ButtonEdit_ButtonClick;
            gridView1.Columns.Add(actionColumn);
            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
            if (gridView1.Columns.Count > 0)
                gridView1.Columns[0].VisibleIndex = 0;
        }

        private void ButtonEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var rowHandle = gridView1.FocusedRowHandle;
            if (rowHandle >= 0)
            {
                var bom = gridView1.GetRow(rowHandle) as BomModel;
                if (bom != null)
                {
                    if (e.Button.Caption == "修改")
                    {
                        var updateForm = new UpdateBomForm(bom);
                        if (updateForm.ShowDialog() == DialogResult.OK)
                        {
                            LoadBomData();
                        }
                    }
                    else if (e.Button.Caption == "删除")
                    {
                        var confirm = XtraMessageBox.Show("确定删除吗", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (confirm == DialogResult.Yes)
                        {
                            if (DeleteBomAsync(bom.Id).Result)
                            {
                                XtraMessageBox.Show("删除成功！");
                                LoadBomData();
                            }
                            else
                            {
                                XtraMessageBox.Show("删除失败！");
                            }
                        }
                    }
                }
            }
        }

        private async Task<bool> DeleteBomAsync(long bomId)
        {
            var response = await _httpClient.PutAsync($"{_bomApiBaseUrl}/api/Bom/DeleteBom?id={bomId}", null);
            return response.IsSuccessStatusCode;
        }

        public class BomModel
        {
            public long Id { get; set; }
            [DisplayName("BOM编号")]
            public string BomCode { get; set; }
            [DisplayName("BOM名称")]
            public string BomName { get; set; }
            [DisplayName("版本号")]
            public string Version { get; set; }
            [DisplayName("类型")]
            public string BomType { get; set; }
            [DisplayName("日产量")]
            public string BomNumber { get; set; }
            [DisplayName("BOM描述")]
            public string BomMsg { get; set; }
            [DisplayName("创建人")]
            public string CreatedBy { get; set; }
            [DisplayName("创建时间")]
            public DateTime CreatedAt { get; set; } = DateTime.Now;
            [DisplayName("修改时间")]
            public DateTime? UpdatedAt { get; set; }
        }

        public class BomListResponse
        {
            public int totalCount { get; set; }
            public List<BomModel> pageDatas { get; set; }
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            var addForm = new AddBomForm();
            if (addForm.ShowDialog() == DialogResult.OK)
            {
                LoadBomData();
            }
        }
        private void btnEdit_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length != 1)
            {
                XtraMessageBox.Show("请只选择一条要修改的数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var bom = gridView1.GetRow(selectedRows[0]) as BomModel;
            if (bom == null)
            {
                XtraMessageBox.Show("未获取到BOM信息！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var updateForm = new UpdateBomForm(bom);
            if (updateForm.ShowDialog() == DialogResult.OK)
            {
                LoadBomData();
            }
        }
        private async void btnDelete_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                XtraMessageBox.Show("请先选择要删除的BOM！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var confirm = XtraMessageBox.Show($"确定要删除选中的 {selectedRows.Length} 个BOM吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirm != DialogResult.Yes) return;

            int successCount = 0;
            int failCount = 0;
            List<string> failedItems = new List<string>();

            foreach (var rowHandle in selectedRows)
            {
                var bom = gridView1.GetRow(rowHandle) as BomModel;
                if (bom != null)
                {
                    if (await DeleteBomAsync(bom.Id))
                    {
                        successCount++;
                    }
                    else
                    {
                        failCount++;
                        failedItems.Add(bom.BomName);
                    }
                }
            }

            string summaryMessage = $"删除操作完成。\n成功: {successCount}个\n失败: {failCount}个";
            if (failCount > 0)
            {
                summaryMessage += "\n失败的BOM：" + string.Join(", ", failedItems);
            }
            XtraMessageBox.Show(summaryMessage, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            if (successCount > 0)
            {
                await LoadBomData();
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadBomData();
        }

        private void EnsureSerialNumberColumn()
        {
            if (gridView1.Columns["序号"] == null)
            {
                var col = gridView1.Columns.AddField("序号");
                col.Caption = "序号";
                col.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
                col.Visible = true;
                col.VisibleIndex = 0;
            }
            else
            {
                gridView1.Columns["序号"].Visible = true;
                gridView1.Columns["序号"].VisibleIndex = 0;
            }
        }

        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "序号" && e.IsGetData)
            {
                e.Value = e.ListSourceRowIndex + 1;
            }
        }

        private void AfterBindBomData()
        {
            EnsureSerialNumberColumn();
            var idColumn = gridView1.Columns["Id"];
            if (idColumn != null) idColumn.Visible = false;
        }
    }
}